# 获取所有环境变量
$envSystem = [System.Environment]::GetEnvironmentVariables("Machine")
$envUser = [System.Environment]::GetEnvironmentVariables("User") 

# 获取 PATH 环境变量
$path = [System.Environment]::GetEnvironmentVariable("PATH", "Machine")
$user_path = [System.Environment]::GetEnvironmentVariable("PATH", "User")

# 将 PATH 按分号分割为各个路径
$paths = $path -split ';'
$user_paths = $user_path -split ';' 

# 定义一个哈希表来存储环境变量和它们的路径
$variablePaths = @{}
$user_variablePaths = @{}

foreach ($envVar in $envSystem.Keys) {
    $variablePaths[$envVar] = [System.Environment]::GetEnvironmentVariable($envVar, "Machine")
}

foreach ($envVar in $envUser.Keys) {
    $user_variablePaths[$envVar] = [System.Environment]::GetEnvironmentVariable($envVar, "User")
}

# 函数：替换路径中的变量
function Replace-PathVariable($paths, $variablePaths) {
    $newPaths = @()
    foreach ($p in $paths) {
        $found = $false
        
        foreach ($var in $variablePaths.Keys) {
            $value = $variablePaths[$var]
            
            if ($p -like "$value*") {
                # 找到匹配的环境变量，替换路径
                $newPath = $p -replace [regex]::Escape($value), "%$var%"
                # Write-Output "Replacing $p with $newPath"
                $newPaths += $newPath
                $found = $true
                break
            }
        }
        
        # 如果没有找到匹配的环境变量，保留原路径
        if (-not $found) {
            $newPaths += $p
          
        }
    }
    return $newPaths -join ';'
}

# 执行路径替换
$newPath = Replace-PathVariable $paths $variablePaths
$newUserPath = Replace-PathVariable $user_paths $user_variablePaths
 $temp =  $newUserPath -split ';'  
 echo  "path_length is  $temp.length" 
 # 更新 PATH 环境变量
[System.Environment]::SetEnvironmentVariable("PATH", $newPath, "Machine")
[System.Environment]::SetEnvironmentVariable("PATH", $newUserPath, "User")

Write-Output "Updated PATH environment variable."